<?php

namespace api\modules\v1\controllers;
use api\common\controllers\CommonController;
use yii\web\ServerErrorHttpException;
use yii\web\HttpException;
use api\modules\v1\models\Code;
use Yii;

class CodeController extends CommonController
{
    public $modelClass = 'api\modules\v1\models\Code';


    public function actions()
    {
        $actions = parent::actions();
        unset($actions['index'],$actions['update'], $actions['create'], $actions['delete'], $actions['view']); //卸载操作
        return $actions;
    }

    /*
     * 发送验证码
     */
    public function actionSend($id){
        $phone = $id;
        if(!preg_match("/^1[34578]{1}\d{9}$/", $phone)){
            throw new HttpException(401,'手机号码格式错误!',0);
        }
        $model = new $this->modelClass();
        $code = $model->makeCode($phone);
        //$code = '123456';
        if($model->saveCode($phone,$code)){
            return [
                'code' => (string)$code,
                'phone' => $phone,
                "message"=>"验证码发送成功!",
            ];
        }elseif (!$model->hasErrors()) {
            throw new ServerErrorHttpException('由于不明原因未能创建对象.');
        }else{
            throw new HttpException(401,array_values($model->getFirstErrors())[0],0);
        }
    }
}
